import * as React from 'react';
import rehypeReact from 'rehype-react';
import CodeMirror from '../CodeMirror';
import { BasicLayout } from '../../layouts';
import DocumentTitle from '../DocumentTitle';
import { P, Enums, Table, Image } from './Widgets';

import styles from './index.module.less';

const renderAst = new rehypeReact({
  createElement: React.createElement,
  components: {
    code: CodeMirror,
    p: P,
    blockquote: Enums,
    table: Table,
    img: Image,
  },
}).Compiler;

const Article = ({ markdownRemark }) => {
  const {
    htmlAst,
    frontmatter: { date, thumbnail, title, metaDescription },
  } = markdownRemark;

  const documentTitleProps = {
    title,
    description: metaDescription,
  };

  return (
    <BasicLayout>
      <DocumentTitle {...documentTitleProps} />
      <article className={styles.article}>
        <div className="article-title-content">
          <h1 className="article-title">{title}</h1>
          <div className="article-date">发布于{date}</div>
        </div>
        {!!thumbnail && (
          <div
            className="article-thumbnail"
            style={{ backgroundImage: `url(${thumbnail})` }}
          ></div>
        )}
        <div className="article-content">{renderAst(htmlAst)}</div>
      </article>
    </BasicLayout>
  );
};

export default React.memo(Article);
